package com.sunspring.zdcall.service.impl;

import com.google.common.collect.Lists;
import com.sunspring.zdcall.bo.UserBo;
import com.sunspring.zdcall.bo.CheckroomBo;
import com.sunspring.zdcall.bo.DeptBo;
import com.sunspring.zdcall.common.constant.enums.StateEnum;
import com.sunspring.zdcall.common.exception.ZdException;
import com.sunspring.zdcall.dto.UserDto;
import com.sunspring.zdcall.mapper.master.UserMapper;
import com.sunspring.zdcall.param.UserParam;
import com.sunspring.zdcall.param.UserSearchParam;
import com.sunspring.zdcall.service.UserService;
import com.sunspring.zdcall.util.Md5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author WuLei
 * @Date 2018/12/3  11:50
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public UserDto selectUser(String username, String password) {
        UserSearchParam usp = new UserSearchParam();
        usp.setUsername(username);
        usp.setPassword(password);
        List<UserDto> list = selectAll(usp);
        if (!CollectionUtils.isEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public void verifyPwd(String username, String oldPwd, String newPwd) {
        UserDto userDto = selectUser(username, oldPwd);
        if (userDto == null) {
            throw new ZdException("账号不存在或密码错误");
        }
        if ((userMapper.verifyPwd(userDto.getUserId(), Md5Util.md5(newPwd))) <= 0) {
            throw new ZdException("修改密码失败");
        }
        log.info("修改密码成功，username={}",username);
    }

    @Override
    public UserDto userLogin(String username, String password) {
        int res = userMapper.selectCountByUsername(username);
        if (res <= 0) {
            throw new ZdException("用户名不存在");
        }
        UserDto userInfo = selectUser(username,Md5Util.md5(password));
        if (userInfo == null) {
            throw new ZdException("密码错误");
        }

        if (userInfo.getUserState() == StateEnum.disable.getCode()) {
            throw new ZdException("账号已被禁用");
        }

        return userInfo;
    }

    @Override
    public List<UserDto> selectAll(UserSearchParam usp) {
        return userMapper.selectSelective(usp);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addNewUser(UserParam userParam) {
        //用户名唯一性校验
        if (userMapper.selectCountByUsername(userParam.getUsername()) > 0) {
            throw new ZdException("用户名已存在");
        }
        //设置用户默认密码
        userParam.setPassword(Md5Util.DEFAULT_PWD);
        userParam.setCreateTime(new Date());
        int result = userMapper.insert(userParam);
        if (result <= 0) {
            throw new ZdException("新增用户失败");
        }
        //添加用户和检查室的映射
        String[] ids = StringUtils.split(userParam.getCheckroomIds(),",");
        result = userMapper.insertBatchUserCheckroomMapping(userParam.getUserId(),ids);
        if (result <= 0) {
            throw new ZdException("新增用户检查映射失败");

        }
    }

    @Override
    public void changeState(int userId) {
        Integer state = userMapper.selectUserStateByUserId(userId);
        int newState = state == StateEnum.enable.getCode() ? StateEnum.disable.getCode() : StateEnum.enable.getCode();
        if (userMapper.updateStateById(userId,newState) <= 0) {
            throw new ZdException("更新用户状态失败");
        }
        if (newState == StateEnum.enable.getCode()) {
            log.info("用户Id:{},已被启用",userId);
        }
        if (newState == StateEnum.disable.getCode()) {
            log.info("用户Id:{},已被停用",userId);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateUser(int userId, String checkroomIds) {
        //删除原先的映射
        int result = userMapper.deleteUserCheckroomMapping(userId);
        if (result <= 0) {
            throw new ZdException("更新异常");
        }
        String[] str = StringUtils.split(checkroomIds,",");
        result = userMapper.insertBatchUserCheckroomMapping(userId,str);
        if (result <= 0) {
            throw new ZdException("更新异常");
        }
    }

    @Override
    public void resetPwd(int userId) {
        int result = userMapper.resetPwd(userId,Md5Util.DEFAULT_PWD);
        if (result <= 0) {
            throw new ZdException("密码重置失败");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println(Md5Util.md5("admin"));

    }

}
